package com.erf.handler.server;

import com.erf.message.BaseMessage;
import com.erf.message.LoginRequestResponse;
import com.erf.tools.SequenceUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
/**
 * @author zhangzy
 * @date 2022/7/5
 */
@Slf4j
public abstract class AbstractBusinessHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String user = ctx.channel().attr(LoginRequestHandler.KEY).get();
        if (user == null) {
            LoginRequestResponse loginRequestResponse = new LoginRequestResponse();
            loginRequestResponse.setSequence(SequenceUtil.getSequenceId());
            loginRequestResponse.setCode(-2);
            loginRequestResponse.setDescription("尚未登录");
            ChannelFuture channelFuture = ctx.writeAndFlush(loginRequestResponse);
            log.info("尚未登录无法接收客户端发送信息！即将关闭channel：" + ctx.channel().id().asShortText());
            //异步关闭
            channelFuture.addListener(future -> {
                Channel channel = ctx.channel();
                log.info("尚未登录无法接收客户端发送信息！正在关闭channel：" + channel.id().asShortText());
                channel.close();
            });
        } else {
                if (msg instanceof BaseMessage) {
                    this.channelRead0(ctx, (BaseMessage)msg);
                } else {
                    //放行给BlackHole
                    ctx.fireChannelRead(msg);
                }
        }
    }

    /**
     * 处理已登录账号接收到的BaseMessage信息
     * @param ctx channelHandler上下文对象
     * @param msg 接受到的baseMessage
     */
    public abstract void channelRead0(ChannelHandlerContext ctx, BaseMessage msg);
}
